package com.bac.bacplatform;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.android.volley.Response.Listener;
import com.bac.javabeans.FuellingCard;
import com.bac.javabeans.GasolinePlan;
import com.bac.javabeans.Page;
import com.bac.javabeans.WealthAccount;
import com.bac.utils.Config;
import com.bac.utils.Util;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class PreferentialGasActivity extends BaseActivity implements OnClickListener {
	private TextView planTV;
	private AutoCompleteTextView mAtCard;
	private EditText phoneNumber;
	private RelativeLayout poly;
	private RelativeLayout advance;
	private RelativeLayout others;
	private ImageView choose_poly;
	private ImageView choose_advance;
	private ImageView choose_others;
//	private ImageButton btClearCard;
	private int progressCount = 0;

	private GasolinePlan mPlan;
	
	// 聚优金余额
	private TextView mRemanding;
	
	// 当前选择支付方式，0(未选择)，1(聚优金)，2(银行卡)
    private int mCurrentPay = 0;
    
 // 卡号数据
 	private ArrayList<String> mCardStrings = new ArrayList<String>();
 	private ArrayList<String> mCardNameString = new ArrayList<String>();
 	
 	private ArrayAdapter<String> mAdapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_preferential_gas);
		
		mPlan = (GasolinePlan)getIntent().getSerializableExtra(GasolinePlan.GASOLINEPLAN_KEY);
		
		getAccountInfo();
		
		mAtCard = (AutoCompleteTextView) findViewById(R.id.preferential_gascard);
		mAdapter = new ArrayAdapter<String>(this, R.layout.drop_down_item, R.id.tv_content, mCardNameString);
		mAtCard.setAdapter(mAdapter);
		mAtCard.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mAtCard.showDropDown();
			}
		});
		
		mAtCard.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String currentCard = mCardNameString.get(position);
				String[] strArray = currentCard.split(" ");
				mAtCard.setText(strArray[0]);
				Log.i("item clicked---", strArray[0]);
				
				 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				 imm.hideSoftInputFromWindow(mAtCard.getWindowToken(), 0);
			}
		});
		
		getHistoryCards();
	}

	@Override
	public void init() {
		planTV = (TextView)findViewById(R.id.tv_coupontype);
		phoneNumber = (EditText) findViewById(R.id.preferential_phoneNumber);
		poly = (RelativeLayout) findViewById(R.id.preferential_polypay_layout);
		advance = (RelativeLayout) findViewById(R.id.preferential_advancepay_layout);
		others = (RelativeLayout) findViewById(R.id.preferential_otherspay_layout);
		choose_advance = (ImageView) findViewById(R.id.choose_advancepay);
		choose_others = (ImageView) findViewById(R.id.choose_others);
		choose_poly = (ImageView) findViewById(R.id.choose_poly);
		mRemanding = (TextView)findViewById(R.id.tv_remaining);

		poly.setOnClickListener(this);
		advance.setOnClickListener(this);
		others.setOnClickListener(this);
		findViewById(R.id.preferential_ok_btn).setOnClickListener(this);
		
		planTV.setText(mPlan.getName());
		phoneNumber.setText(Config.UserGeneralInfo.phone);
		
		
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.preferential_polypay_layout:
			chooseChange(1);
			break;
		case R.id.preferential_advancepay_layout:
			chooseChange(2);
			break;
		case R.id.preferential_otherspay_layout:
			chooseChange(3);
			break;
		case R.id.preferential_ok_btn:
			goPayment();
			break;
		default:
			break;
		}
	}

	public void goPayment(){
		if (mAtCard.getText().toString().length() == 0) {
			showToast("请输入卡号");
			return;
		}else if(phoneNumber.getText().toString().length() == 0){
			showToast("请输入手机号");
			return;
		}else if(mCurrentPay == 0){
			showToast("请选择支付方式");
			return;
		}
		
		if (mCardNameString.size()==0 || !mCardStrings.contains(mAtCard.getText().toString().trim())) {
			checkFuellingCard(mAtCard.getText().toString().trim());
			return;
		}
		
		if (mCurrentPay == 1) {// 聚优金支付
			payForJuyoujin();
		}else if (mCurrentPay == 3) {// 银行卡支付
			payForYeepay();
		}
		
	}
	
	/**
	 * 获取账户信息
	 */
	public void getAccountInfo(){
		
		Listener<String> sListener = new Listener<String>() {
			@Override
			public void onResponse(String response) {
				progressCount++;
				if (progressCount == 2) {
					dismissLoadingProgress();
				}
				Log.i(getClass().getName(), "success---"+response.toString());
				Gson gson = new Gson();
				WealthAccount account = gson.fromJson(response, WealthAccount.class);
				mRemanding.setText(account.getBalance().toString());
			}
		};
		showLoadingProgress();
		String path = Config.URL_GET_WEALTHACCOUNTINFO;
		Util.httpRequestToGet(path, sListener, this);
	}
	
	/**
	 * 聚优金支付
	 */
	public void payForJuyoujin(){
		
		Listener<String> sListener = new Listener<String>() {
			@Override
			public void onResponse(String response) {
				dismissLoadingProgress();
				Log.i(getClass().getName(), response.toString());
				HashMap<String, String> result = new Gson().fromJson(response.toString().trim(),
						new TypeToken<HashMap<String, String>>() {
						}.getType());
				if (result != null && result.containsKey("balance")) {
					mRemanding.setText(result.get("balance"));
				}
				
				AlertDialog.Builder builder = new AlertDialog.Builder(PreferentialGasActivity.this, R.style.Custom_dialog);
				final AlertDialog alertDialog = builder.create();
				alertDialog.show();
				Window window = alertDialog.getWindow();
				View view = LayoutInflater.from(PreferentialGasActivity.this).inflate(R.layout.dialog_alert, null);
				((TextView)(view.findViewById(R.id.tv_title))).setText("提示");
				((TextView)(view.findViewById(R.id.tv_message))).setText("支付成功");
				view.findViewById(R.id.ly_ok).setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						alertDialog.dismiss();
						finishActivityOut();
					}
				});
				window.setContentView(view);
				window.setLayout((int)(Util.getWidth(getApplicationContext()) * 0.8), WindowManager.LayoutParams.WRAP_CONTENT);
			}
		};
		showLoadingProgress();
		String path = Config.URL_PAY_JUYOUJIN;
		Map<String, String> map = new HashMap<String, String>();
		map.put("amount", mPlan.getAmount().toString());
		map.put("account", mAtCard.getText().toString());
		map.put("terminalId", Util.getDeviceID(PreferentialGasActivity.this));
		map.put("transactionCode", "GAS004");
		map.put("productCode", mPlan.getId().toString());
		map.put("phone", phoneNumber.getText().toString().trim());
		Util.httpStringPost(path, sListener, this, map);
		
	}
	
	/**
	 * 易宝支付
	 */
	public void payForYeepay(){
		Listener<String> sListener = new Listener<String>() {
			@Override
			public void onResponse(String response) {
				dismissLoadingProgress();
				Log.i("PreferentialGasActivity----success", response.toString());
				HashMap<String, String> result = new Gson().fromJson(response.toString().trim(),
						new TypeToken<HashMap<String, String>>() {
						}.getType());
				
				if (result != null && result.containsKey("paymentUrl")) {
					Intent intentToPay = new Intent(PreferentialGasActivity.this, YeepayActivity.class);
					intentToPay.putExtra("paymentUrl", result.get("paymentUrl"));
					startActivityIn(intentToPay);
				}
			}
		};
		showLoadingProgress();
		String path = Config.URL_YEEPAY;
		Map<String, String> map = new HashMap<String, String>();
		map.put("amount", mPlan.getAmount().toString());
		map.put("account", mAtCard.getText().toString());
		map.put("terminalId", Util.getDeviceID(PreferentialGasActivity.this));
		map.put("transactionCode", "GAS004");
		map.put("productCode", mPlan.getId().toString());
		Util.httpStringPost(path, sListener, this, map);
	}
	
	
	public void chooseChange(int id) {
		choose_poly.setVisibility(View.INVISIBLE);
		choose_advance.setVisibility(View.INVISIBLE);
		choose_others.setVisibility(View.INVISIBLE);

		switch (id) {
		case 1:
			choose_poly.setVisibility(View.VISIBLE);
			mCurrentPay = 1;
			break;
		case 2:
			choose_advance.setVisibility(View.VISIBLE);
			mCurrentPay = 2;
			break;
		case 3:
			choose_others.setVisibility(View.VISIBLE);
			mCurrentPay = 3;
			break;

		default:
			mCurrentPay = 0;
			break;
		}
	}

	@Override
	public void hanlderTimeoutError() {
		// TODO Auto-generated method stub
		super.hanlderTimeoutError();
	}

	@Override
	public void hanlderErrorShowMessage(String string) {
		super.hanlderErrorShowMessage(string);
	}

	@Override
	public void hanlderAutorError() {
		// TODO Auto-generated method stub
		super.hanlderAutorError();
	}

	@Override
	public void hanlderUnknowError() {
		// TODO Auto-generated method stub
		super.hanlderUnknowError();
	}

	@Override
	public void hanlderNetworkError() {
		// TODO Auto-generated method stub
		super.hanlderNetworkError();
	}
	
	public void getHistoryCards() {
		Listener<String> sListener = new Listener<String>() {
			@SuppressWarnings("rawtypes")
			@Override
			public void onResponse(String response) {
				progressCount++;
				if (progressCount == 2) {
					dismissLoadingProgress();
				}
				Log.i("getcards----success", response.toString());
				Gson gson = new Gson();
				java.lang.reflect.Type type = new TypeToken<Page>(){}.getType();
				Page page = gson.fromJson(response, type);
				@SuppressWarnings("unchecked")
				List<FuellingCard> cards = page.getList();
				for (int i = 0; i < cards.size(); i++) {
					// 卡号后面加上名字
					mCardNameString.add(cards.get(i).getCardNo() +" "+ cards.get(i).getCardOwner());
					// 卡号添加到数组，方便后续校验
					mCardStrings.add(cards.get(i).getCardNo());
				}
				mAdapter.notifyDataSetChanged();
			}
		};
		showLoadingProgress();
		
		String path = Config.URL_GET_CARDS;
		Map<String, String> map = new HashMap<String, String>();
		// 默认是第一页，每页20条，这里没有传参数，最多取20条
		// 如果需要传参数，可以使用Util.httpRequestToGetWithParams(url, l, el, map)
		map.put("pageNo", "1");
		map.put("pageSize", "20");
//		Util.httpRequestToGet(path, sListener, this);
		Util.httpRequestToGetWithParams(path, sListener, this, map);
	}
	
	public void checkFuellingCard(String carNo){
		Listener<String> sListener = new Listener<String>() {
			@Override
			public void onResponse(String response) {
				dismissLoadingProgress();
				Log.i("PreferentialGasActivity----success", response.toString());
				Gson gson = new Gson();
				FuellingCard fuellingCard = gson.fromJson(response, FuellingCard.class);
				// 计算卡号后四位
				String cardNo = fuellingCard.getCardNo();
				String card4 = cardNo.substring(cardNo.length() - 4, cardNo.length());
				String info = String.format(getString(R.string.commen_dialog_message4), card4, fuellingCard.getCardOwner());
				
					AlertDialog.Builder builder = new AlertDialog.Builder(PreferentialGasActivity.this, R.style.Custom_dialog);
					final AlertDialog alertDialog = builder.create();
					alertDialog.setCanceledOnTouchOutside(false);
					alertDialog.show();
					Window window = alertDialog.getWindow();
					View view = LayoutInflater.from(PreferentialGasActivity.this).inflate(R.layout.dialog_alert, null);
					view.findViewById(R.id.ly_cancel).setVisibility(View.VISIBLE);
					view.findViewById(R.id.line).setVisibility(View.VISIBLE);
					
					((TextView)(view.findViewById(R.id.tv_title))).setText(getString(R.string.commen_dialog_title1));
					((TextView)(view.findViewById(R.id.tv_message))).setText(Html.fromHtml(info));
					
					view.findViewById(R.id.ly_cancel).setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							alertDialog.dismiss();
						}
					});
					
					view.findViewById(R.id.ly_ok).setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							alertDialog.dismiss();
							if (mCurrentPay == 1) {// 聚优金支付
								payForJuyoujin();
							}else if (mCurrentPay == 3) {// 银行卡支付
								payForYeepay();
							}
						}
					});
					window.setContentView(view);
					window.setLayout((int)(Util.getWidth(getApplicationContext()) * 0.8), WindowManager.LayoutParams.WRAP_CONTENT);
					
			}
		};
		showLoadingProgress();
		String path = Config.URL_CHECK_CARD;
		Map<String, String> map = new HashMap<String, String>();
		map.put("cardNo", carNo);
		map.put("terminalId", Util.getDeviceID(PreferentialGasActivity.this));
		Util.httpStringPost(path, sListener, this, map);
	}
	
}
